package com.power.sifa.approve.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.aventrix.jnanoid.jnanoid.NanoIdUtils;
import com.plf.common.domain.PageDataResponse;
import com.plf.common.file.model.FileVo;
import com.plf.common.utils.PdfConvertUtil;
import com.plf.common.utils.StringUtil;
import com.plf.common.utils.WordUtil;
import com.plf.core.base.model.Ha_attachment;
import com.plf.core.base.service.Ha_attachmentService;
import com.plf.core.common.dao.OffersetTransformers;
import com.plf.core.common.file.FileController;
import com.plf.core.common.service.BaseServiceImpl;
import com.power.sifa.approve.dao.Apl_admre_auditDao;
import com.power.sifa.approve.dao.Aprv_process_materialsDao;
import com.power.sifa.approve.model.Apl_admre_audit;
import com.power.sifa.approve.model.Apl_main;
import com.power.sifa.approve.model.Aprv_materials_customer;
import com.power.sifa.approve.model.Aprv_process_materials;
import com.power.sifa.approve.model.enumeration.Tp_classifyEnum;
import com.power.sifa.approve.model.enumeration.Tp_procmaterialEnum;
import com.power.sifa.approve.model.enumeration.Tp_proctype;
import com.power.sifa.approve.model.enumeration.Tp_proctypeEnum;
import com.power.sifa.approve.model.pageInfo.Aprv_process_materialsPageInfo;
import com.power.sifa.approve.service.Apl_mainService;
import com.power.sifa.approve.service.Aprv_materials_customerService;
import com.power.sifa.approve.service.Aprv_materials_optionsService;
import com.power.sifa.approve.service.Aprv_process_materialsService;
import com.power.sifa.net.service.ApplyService;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.query.internal.NativeQueryImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 审批过程材料业务层实现
 */
@Slf4j
@Service
public class Aprv_process_materialsServiceImpl extends BaseServiceImpl implements Aprv_process_materialsService {

    @Resource
    private Aprv_process_materialsDao dao;
    @Resource
    private Ha_attachmentService ha_attachmentService;
    @Resource
    private Aprv_materials_customerService aprv_materials_customerService;
    @Resource
    private Apl_admre_auditDao apl_admre_auditDao;
    @Resource
    private ApplyService applyService;
    @Resource
    private Apl_mainService apl_mainService;
    @Resource
    private FileController fileController;
    @Value("${minio.bucket:#{null}}")
    private String bucketName;

    @Resource
    private  EntityManager entityManager;

    @Resource
    private Aprv_materials_optionsService aprv_materials_optionsService;

    @Override
    public Aprv_process_materials getById(Serializable id) {
        return dao.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Aprv_process_materials aprv_process_materials) {
        // save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (aprv_process_materials.getPrimaryKey() != null) {
            Aprv_process_materials aprv_process_materialsfDb = dao.findById(aprv_process_materials.getPrimaryKey()).orElse(null);
            if (aprv_process_materialsfDb != null) {
                BeanUtils.copyProperties(aprv_process_materials, aprv_process_materialsfDb);
                dao.save(aprv_process_materialsfDb);
                return;
            }
        }
        dao.save(aprv_process_materials);
    }

    @Override
    public void removeById(Serializable id) {
        dao.deleteById(id);
    }

    @Override
    public Page<Aprv_process_materials> findAll(Aprv_process_materialsPageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if ("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        } else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber() <= 1 ? 0 : pageInfo.getPageNumber() - 1, pageInfo.getPageSize(), sort);
        //查询条件
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec, pageable);
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<Integer> ids) {
        dao.removeByIds(ids);
    }

    @Override
    public List<Aprv_process_materials> findAll() {
        return dao.findAll();
    }

    @Override
    public void saveAll(List<Aprv_process_materials> list) {
        dao.saveAll(list);
    }


    /**
     * 通过保存后的文件更新材料表的关联关系-单条数据
     *
     * @param attachId
     * @param applyId
     * @param busiType
     * @param userId
     * @param userName
     * @param fileEnum
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Aprv_process_materials saveMaterial(String attachId, String applyId, Integer busiType, String userId,
                                               String userName, Tp_procmaterialEnum fileEnum) {
        String key = applyId + NanoIdUtils.randomNanoId();
        Aprv_process_materials materialNew = new Aprv_process_materials(fileEnum);
        materialNew.setApplyid(applyId);
        materialNew.setType(busiType);
        materialNew.setMattype(fileEnum.getId());
        materialNew.setAttachid(attachId);
        materialNew.setCreateuser(userName);
        materialNew.setCreateuserid(userId);
        materialNew.setCreatetime(new Date());
        materialNew.setId(key);
        materialNew.setCreatetime(new Date());
        dao.save(materialNew);
        List<Aprv_process_materials> attachMentList = new ArrayList<>();
        attachMentList.add(materialNew);
        findAttachMentByMeterial(attachMentList);
        // 记录初始化版本记录
        CompletableFuture.runAsync(() -> this.aprv_materials_optionsService.initMaterialOptions(materialNew, userId));
        return attachMentList.get(0);
    }


    /**
     * 通过保存后的文件更新材料表的关联关系-多条数据
     *
     * @param file
     * @param applyId
     * @param busiType
     * @param userId
     * @param userName
     * @param fileEnum
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Aprv_process_materials saveMaterialRepeat(FileVo file, String applyId, Integer busiType, String userId,
                                                     String userName, Tp_procmaterialEnum fileEnum) {
        // 查询对应的业务申请id是否有对应文件类型的数据
        // 修改为支持多文件上传，支持多个文件保存
        String key = applyId + NanoIdUtils.randomNanoId();
        Aprv_process_materials material = new Aprv_process_materials(fileEnum);
        material.setId(key);
        material.setApplyid(applyId);
        material.setType(busiType);
        material.setMattype(fileEnum.getId());
        material.setAttachid(file.getId());
        material.setCreateuser(userName);
        material.setCreateuserid(userId);
        material.setCreatetime(new Date());
        dao.save(material);
        List<Aprv_process_materials> attachMentList = new ArrayList<>();
        attachMentList.add(material);
        findAttachMentByMeterial(attachMentList);
        // 记录初始化版本记录
        CompletableFuture.runAsync(() -> this.aprv_materials_optionsService.initMaterialOptions(material,userId));
        return attachMentList.get(0);
    }

    /**
     * 保存自定义材料类型文件
     *
     * @param file            文件vo
     * @param applyId
     * @param busiType        业务类型
     * @param userId
     * @param userName
     * @param replyCustomerId 自定义材料类型id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Aprv_process_materials saveMaterialCustomer(FileVo file, String applyId, Integer busiType, String userId, String userName, String replyCustomerId) {
        String key = applyId + NanoIdUtils.randomNanoId();
        Aprv_process_materials material = new Aprv_process_materials();
        // 自定义材料类型默认是材料类型并且没有对应的阶段分类
        material.setClassify(Tp_classifyEnum.MATERIAL.getId());
        material.setId(key);
        material.setApplyid(applyId);
        material.setType(busiType);
        // 默认自定义材料类型
        material.setMattype(Tp_procmaterialEnum.MATER_CUSTOMER.getId());
        material.setAttachid(file.getId());
        material.setCreateuser(userName);
        material.setCreateuserid(userId);
        material.setCreatetime(new Date());
        material.setReply_attachid(replyCustomerId);
        dao.save(material);
        List<Aprv_process_materials> attachMentList = new ArrayList<>();
        attachMentList.add(material);
        findAttachMentByMeterial(attachMentList);
        // 记录初始化版本记录
        CompletableFuture.runAsync(() -> this.aprv_materials_optionsService.initMaterialOptions(material, userId));
        return attachMentList.get(0);
    }

    /**
     * 查询材料的文件地址
     *
     * @param materials
     */
    @Override
    public void findAttachMentByMeterial(List<Aprv_process_materials> materials) {
        if (CollectionUtil.isNotEmpty(materials)) {
            List<String> attachmentIds = materials.stream().map(Aprv_process_materials::getAttachid).collect(Collectors.toList());
            Map<String, Ha_attachment> ha_attachmentMap = ha_attachmentService.getHa_attachmentsByIds(attachmentIds);
            if (ObjectUtil.isNotNull(ha_attachmentMap)) {
                materials.stream().forEach(m -> {
                    Optional.ofNullable(ha_attachmentMap.get(m.getAttachid())).ifPresent(then -> {
                        m.setFile(ha_attachmentMap.get(m.getAttachid()));
                    });
                });
            }
        }
    }

    /**
     * 设置自定义材料
     *
     * @param applyid
     * @param materials
     */
    private void setCustomerMaterials(String applyid, List<Aprv_process_materials> materials) {
        findAttachMentByMeterial(materials);
        List<Aprv_materials_customer> customerMaterials = aprv_materials_customerService.listCustomerByApplyid(applyid);
        // 设置自定义材料类型
        if (CollectionUtil.isNotEmpty(customerMaterials)) {
            materials.stream().filter(element -> ObjectUtil.isNotEmpty(element.getReply_attachid())).forEach(element -> {
                element.setCustomerMaterial(customerMaterials.stream().filter(customer -> customer.getId().equals(element.getReply_attachid())).findAny().orElse(null));
            });
        }
    }

    /**
     * 查询全部的材料文件 包含系统文件和过程材料
     *
     * @param applyid
     * @return
     */
    @Override
    public List<Aprv_process_materials> getAllMaterialByApplyId(String applyid) {
        Specification<Aprv_process_materials> specification = (root, query, criteriaBuilder) -> query.where(
                criteriaBuilder.equal(root.get("applyid"), applyid)
        ).getRestriction();
        Sort sort = Sort.by(Sort.Direction.DESC, "createtime");
        List<Aprv_process_materials> materials = dao.findAll(specification, sort);
        if (CollectionUtils.isEmpty(materials)) {
            return Collections.emptyList();
        }
        setCustomerMaterials(applyid, materials);
        return materials;
    }

    /**
     * 查询全部的过程材料文件
     *
     * @param applyid
     * @return
     */
    @Override
    public List<Aprv_process_materials> queryMaterialByApplyId(String applyid) {
        // 查询过程材料
        Specification<Aprv_process_materials> specification = (root, query, criteriaBuilder) -> query.where(
                criteriaBuilder.and(criteriaBuilder.equal(root.get("applyid"), applyid),
                        criteriaBuilder.and(criteriaBuilder.equal(root.get("classify"), Tp_classifyEnum.MATERIAL.getId())))
        ).getRestriction();
        Sort sort = Sort.by(Sort.Direction.DESC, "createtime");
        List<Aprv_process_materials> materials = dao.findAll(specification, sort);
        if (CollectionUtils.isEmpty(materials)) {
            return Collections.emptyList();
        }
        setCustomerMaterials(applyid, materials);
        return materials;
    }

    @Override
    public PageDataResponse getMaterialList(Aprv_process_materialsPageInfo pageInfo) {
        List<Aprv_process_materials> list = this.dao.getMaterialList(pageInfo);

        // 分页
        PageDataResponse page = new PageDataResponse();
        if (CollectionUtil.isNotEmpty(list)) {
            findAttachMentByMeterial(list);
            Long total = Long.valueOf(pageInfo.getAllcount());
            int size = pageInfo.getPageSize() * pageInfo.getPageNumber();
            if (total.intValue() - size > 0) {
                page.setNextPage(pageInfo.getPageNumber() + 1);
            }
            page.setSize(pageInfo.getPageSize());
            page.setCurrent(pageInfo.getPageNumber());
            page.setTotal(total);
        } else {
            page.setSize(0);
            page.setCurrent(1);
            page.setTotal(0L);
        }
        page.setRecords(list);
        return page;
    }

    /**
     * 查询系统文书
     *
     * @param applyid
     * @return
     */
    @Override
    public List<Aprv_process_materials> queryDocumentByApplyId(String applyid) {
        Specification<Aprv_process_materials> specification = (root, query, criteriaBuilder) -> query.where(
                criteriaBuilder.and(criteriaBuilder.equal(root.get("applyid"), applyid), criteriaBuilder.or(criteriaBuilder.equal(root.get("classify"),
                        Tp_classifyEnum.DOCUMENT.getId()), criteriaBuilder.equal(root.get("classify"), Tp_classifyEnum.MATANDDOC.getId())))
        ).getRestriction();
        Sort sort = Sort.by(Sort.Direction.DESC, "createtime");
        List<Aprv_process_materials> materials = dao.findAll(specification, sort);
        if (CollectionUtils.isEmpty(materials)) {
            return Collections.emptyList();
        }
        setCustomerMaterials(applyid, materials);
        return materials;
    }

    /**
     * 查询全部的文件
     *
     * @param applyid
     * @return
     */
    @Override
    public List<Aprv_process_materials> queryAttachByApplyId(String applyid) {
        Specification<Aprv_process_materials> specification = (root, query, criteriaBuilder) -> query.where(
                criteriaBuilder.and(criteriaBuilder.equal(root.get("applyid"), applyid))
        ).getRestriction();
        Sort sort = Sort.by(Sort.Direction.DESC, "createtime");
        List<Aprv_process_materials> materials = dao.findAll(specification, sort);
        if (CollectionUtils.isEmpty(materials)) {
            return Collections.emptyList();
        }
        setCustomerMaterials(applyid, materials);
        return materials;
    }

    @Override
    public List<Aprv_process_materials> findByIds(List<String> ids) {
        Specification<Aprv_process_materials> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> param = new ArrayList<>();
            //ids in
            if (null != ids && ids.size() > 0) {
                CriteriaBuilder.In<String> in = criteriaBuilder.in(root.get("id"));
                for (String id : ids) {
                    in.value(id);
                }
                param.add(in);
            }
            return criteriaBuilder.and(param.toArray(new Predicate[param.size()]));
        };
        List<Aprv_process_materials> materials = dao.findAll(specification);
        if (CollectionUtils.isEmpty(materials)) {
            return Collections.emptyList();
        }
        findAttachMentByMeterial(materials);
        return materials;
    }


    /**
     * 通过自定义材料类型删除材料
     *
     * @param customerId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByCustomerId(String customerId) {
        // 删除对应的附件表数据
        Specification<Aprv_process_materials> specification = (root, query, criteriaBuilder) -> query.where(
                criteriaBuilder.equal(root.get("reply_attachid"), customerId)
        ).getRestriction();
        List<Aprv_process_materials> materials = dao.findAll(specification);

        if (CollectionUtil.isNotEmpty(materials)) {
            List<String> attachIds = materials.stream().map(Aprv_process_materials::getAttachid).collect(Collectors.toList());
            this.ha_attachmentService.removeByIds(attachIds);
            List<String> ids = materials.stream().map(Aprv_process_materials::getId).collect(Collectors.toList());
            this.dao.deleteAllById(ids);
        }
    }

    @Override
    public void regeneration() throws Exception {
        List<Integer> mattypes = new ArrayList<>();
        mattypes.add(6003734);
        mattypes.add(6003731);
        mattypes.add(6003727);
        mattypes.add(6003736);
        List<Aprv_process_materials> list = this.dao.getMaterialByMattypes(mattypes, "2024-03-01");
        if (!CollectionUtils.isEmpty(list)) {
            for (Aprv_process_materials v : list) {
                List<Apl_admre_audit> auditList = this.apl_admre_auditDao.getListByApplyid(v.getApplyid());
                try {
                    if (!CollectionUtils.isEmpty(auditList)) {
                        if (auditList.size() == 1) {
                            log.info("单条更新 -> " + v.getId());
                            // 只有一条记录就拿这一个记录去生成审批表, 其它的拿人工生成审批表
                            Apl_main mainSonObj = this.apl_mainService.getById(auditList.get(0).getId());
                            String attachmentid = this.buildDoc(mainSonObj.getId(), v.getMattype(), mainSonObj.getFormid(), auditList.get(0));
                            // 删除旧文件, 引用新文件id
                            this.fileController.minioRemove(bucketName, v.getAttachid());
                            this.dao.updateAttachid(v.getId(), attachmentid);
                        } else {
//                        log.info("多条记录 -> {}", v.getId());
                            // 多条记录比较文书生成最接近的一条, 重新生成
                            long createtime = v.getCreatetime().getTime();
                            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            List<Integer> numbers = new ArrayList<>(auditList.size());
                            Map<String, Apl_admre_audit> tempMap = new HashMap<>(16);
                            for (Apl_admre_audit audit : auditList) {
                                if (audit.getFirstdate() == null) {
                                    continue;
                                }
                                long firstdate = dateFormat.parse(audit.getFirstdate()).getTime();
                                if (firstdate > createtime) {
                                    continue;
                                }
                                // 差值结果最小值最接近
                                Integer result = (int) (createtime - firstdate);
                                tempMap.put(String.valueOf(result), audit);
                                numbers.add(result);
                            }
                            if (!CollectionUtils.isEmpty(numbers)) {
                                int min = Collections.min(numbers);
                                log.info("多条记录 -> {}", tempMap.get(String.valueOf(min)).getId());
                                Apl_main mainSonObj = this.apl_mainService.getById(tempMap.get(String.valueOf(min)).getId());
                                String attachmentid = this.buildDoc(mainSonObj.getId(), v.getMattype(), mainSonObj.getFormid(), tempMap.get(String.valueOf(min)));
                                // 删除旧文件, 引用新文件id
                                this.fileController.minioRemove(bucketName, v.getAttachid());
                                this.dao.updateAttachid(v.getId(), attachmentid);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("文书重新生成失败id: {} ->  msg[{}]", v.getId(), e.getMessage());
                }

            }
        }
    }

    @Override
    public List<Aprv_process_materials> getAllMaterialByAttachId(String attachId) {
        Specification<Aprv_process_materials> specification = (root, query, criteriaBuilder) -> query.where(
                criteriaBuilder.and(criteriaBuilder.equal(root.get("attachid"), attachId))
        ).getRestriction();
        List<Aprv_process_materials> materials = dao.findAll(specification);
        if (CollectionUtils.isEmpty(materials)) {
            return Collections.emptyList();
        }
        findAttachMentByMeterial(materials);
        return materials;
    }

    public String buildDoc(String applyid, Integer mattype, String formid, Apl_admre_audit auditObj) throws Exception {
        Ha_attachment attachment;
        Map<String, Object> formData = this.applyService.formLoadField(formid, applyid);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat formatT = new SimpleDateFormat("yyyy年M月d日");
        if (!StringUtil.isEmpty(formData.get("apl_admre_audit_firstdate"))) {
            formData.put("apl_admre_audit_firstdate", formatT.format(format.parse((String) formData.get("apl_admre_audit_firstdate"))));
        }
        if (!StringUtil.isEmpty(formData.get("apl_admre_audit_seconddate"))) {
            formData.put("apl_admre_audit_seconddate", formatT.format(format.parse((String) formData.get("apl_admre_audit_seconddate"))));
        }
        if (!StringUtil.isEmpty(formData.get("apl_admre_audit_thirddate"))) {
            formData.put("apl_admre_audit_thirddate", formatT.format(format.parse((String) formData.get("apl_admre_audit_thirddate"))));
        }
        if (!StringUtil.isEmpty(formData.get("apl_admre_audit_fourthdate"))) {
            formData.put("apl_admre_audit_fourthdate", formatT.format(format.parse((String) formData.get("apl_admre_audit_fourthdate"))));
        }
        if (!StringUtil.isEmpty(formData.get("apl_admre_audit_fivedate"))) {
            formData.put("apl_admre_audit_fivedate", formatT.format(format.parse((String) formData.get("apl_admre_audit_fivedate"))));
        }

        byte[] pdfByte;

        OutputStream os = null;
        InputStream is = null;
        {
            try {
                String filename;
                WordUtil wordUtil;
                switch (auditObj.getType()) {
                    case Tp_proctype.ACCEPT_APPEND:
                    case  Tp_proctype.MATER_MEDIATE:
                    case  Tp_proctype.ACCEPT_ACCEPT:
                    case  Tp_proctype.ACCEPT_INFORM:
                    case  Tp_proctype.ACCEPT_NOACCEPT:
                    case  Tp_proctype.ACCEPT_RESULT:
                    case  Tp_proctype.ACCEPT_OTHERDEAL:
                    case  Tp_proctype.ACCEPT_CHANGE_FIRSTPER:
                    case  Tp_proctype.ACCEPT_CHANGE_SECONDPER: {
                        wordUtil = new WordUtil("AdmreAuditInCharge.docx");
                        filename = "行政复议案件审批表.pdf";
                        break;
                    }
                    case  Tp_proctype.HEAR_MEDIATE:
                    case  Tp_proctype.HEAR_TRAWL:
                    case  Tp_proctype.HEAR_INQUEST:
                    case  Tp_proctype.HEAR_HEARING:
                    case  Tp_proctype.HEAR_IDENTIFY:
                    case  Tp_proctype.HEAR_STOP:
                    case  Tp_proctype.HEAR_DELAY:
                    case  Tp_proctype.HEAR_REST:
                    case  Tp_proctype.HEAR_DECISION:
                    case  Tp_proctype.HEAR_WITHDRAW:
                    case  Tp_proctype.HEAR_MOBILIZE:
                    case  Tp_proctype.HEAR_RESTORE:
                    case  Tp_proctype.HEAR_TRANSFORM:
                    case  Tp_proctype.HEAR_EXPERT:
                    case  Tp_proctype.EXECUTE_FORCE_UNIT:
                    case  Tp_proctype.EXECUTE_FORCE_LAW:
                    case  Tp_proctype.EXECUTE_PERFORM: {
                        wordUtil = new WordUtil("ThreeLevelApprove.docx");
                        filename = "行政复议案件审批表.pdf";
                        break;
                    }
                    default: {
                        throw new RuntimeException("buildDoc 未知的文书类型");
                    }
                }
                wordUtil.replaceTable(formData);
                os = wordUtil.createWord();
                        is = new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray());
                pdfByte = PdfConvertUtil.word2pdfWithFont(is);
                attachment = ha_attachmentService.upload(new ByteArrayInputStream(pdfByte), filename);
                log.info(filename + "生成并保存成功 -> {}", attachment.getId());
            } catch (Exception e) {
                log.error("审批表生成并保存失败 ->  msg[{}]", e.getMessage());
                throw new RuntimeException("审批表生成并保存失败 -> " + e.getMessage());
            } finally {
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
            }
            return attachment.getId();
        }
    }


    @Override
    public String getAttachmentByPath(String path) {
        String sql ="select id from ha_attachment where path like ?";
        Query query = entityManager.createNativeQuery((sql));
        query.unwrap(NativeQueryImpl.class).setResultTransformer(OffersetTransformers.ALIAS_TO_ENTITY_MAP);
        query.setParameter(1, "%" + path + "%");
        List resultList = query.getResultList();
        if (CollectionUtil.isNotEmpty(resultList)) {
            Map result = JSON.parseObject(JSON.toJSONString(resultList.get(0)), Map.class);
            return (String) result.get("id");
        }
        return null;
    }

}
